/**
 * 
 */
package forarijit;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import partitioner.PartitionDAO;

import com.puneet.graphqueries.graphs.MapPartitionImpl;

/**
 * @author puneet
 * 
 */
public class NodeCountCalculator {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		File f = new File(args[0]);
		int k = Integer.parseInt(args[1]);
		File queriesFile = new File(args[2]);
		PartitionDAO dao = new MapPartitionImpl(f);
		BufferedReader br = new BufferedReader(new FileReader(queriesFile));
		String s = null;
		Map<String, Integer> nodeCountMap = new HashMap<String, Integer>();
		System.out.println("Starting Node Counting");
		while ((s = br.readLine()) != null) {
			handleNode(s, 0, k, dao, nodeCountMap);
		}
		System.out.println("Done building node count map now outputting");
		for(Entry<String, Integer> nodeCountEntry : nodeCountMap.entrySet()) {
			System.out.println(nodeCountEntry.getKey() + " " + nodeCountEntry.getValue());
		}
	}

	private static void handleNode(String node, int nodek, int k, PartitionDAO dao, Map<String, Integer> nodeCountMap)
			throws Exception {
		if (k == nodek) {
			return;
		}
		addOrIncrement(node, nodeCountMap);
		List<String> neighbors = dao.getNeighbors(node);
		if (nodek < k - 1) {
			for (String neighbor : neighbors) {
				handleNode(neighbor, nodek + 1, k, dao, nodeCountMap);
			}
		}

	}

	private static void addOrIncrement(String node, Map<String, Integer> nodeCountMap) {
		if (nodeCountMap.containsKey(node)) {
			nodeCountMap.put(node, nodeCountMap.get(node) + 1);
		} else {
			nodeCountMap.put(node, 1);
		}

	}

}
